import pdfplumber
from as400_insert_db import as400_sync
import time
import pandas as pd


class PDF_EXCEL():
    def __init__(self):
        path = r"E:\OCR_RMC\ORC_BAR2.0\pdf_excel\img\123.pdf"
        self.pdf = pdfplumber.open(path)   # OBJ
        self.pdf_data_List = []
        self.pdf_dict = {}

        self.all_List = []


    # 去噪点
    def del_EG(self, pdf_data):
        for index, pdf_str in enumerate(pdf_data):
            if pdf_str == "E" or pdf_str == "G" or pdf_str == "G *" or pdf_str == "  *":
                del pdf_data[index]
        return pdf_data
    # 获取厂家
    def get_plant_time(self, pdf_data):
        RMC_list = pdf_data[3].strip().split(" ")
        plant = RMC_list[0]
        data = RMC_list[5]
        time = RMC_list[6]
        self.pdf_dict["plant"] = int(plant)
        self.pdf_dict["data"] = int(data)
        self.pdf_dict["time"] = int(time)

    # 获取发票时间
    def get_invoice_time(self, pdf_data):
        pdf_str2 = pdf_data[2].strip().split(" ")
        self.pdf_dict["invoice_time"] = int(pdf_str2[3])

    # 获取 区域代码, 线名 ,工位
    def get_area_line(self, pdf_data):
        pdf_str_0 = pdf_data[0].strip().split(" ")
        self.pdf_dict["lineName"] = pdf_str_0[0]
        self.pdf_dict["area_code"] = pdf_str_0[2]

    def get_RMC(self, pdf_data):
        for pdf_RMCstr in pdf_data[4:]:
            pdf_RMCstrList = pdf_RMCstr.strip().split(" ")
            self.pdf_dict["RMC_bar"] = pdf_RMCstrList[1]             # 部番
            self.pdf_dict["ticket_bar"] = int(pdf_data[1])       # 出张出库票
            self.pdf_dict["demand"] = int(pdf_RMCstrList[3])     # 需求数
            self.pdf_dict["BOX"] = int(pdf_RMCstrList[5])        # 胶箱数
            self.pdf_dict["BOX_num"] = int(pdf_RMCstrList[4])    # 箱入数
            self.pdf_dict["REQ"] = int(pdf_RMCstrList[6])         # 箱入数
            self.pdf_dict["serial_num"] = int(pdf_RMCstrList[0])   # 序号(serial_num)
            self.pdf_dict["station"] = pdf_RMCstrList[7]    # 工位
            self.get_plant_time(pdf_data)     # 获取厂家
            self.get_invoice_time(pdf_data)   # 获取发票时间
            self.get_area_line(pdf_data)        # 获取 区域代码, 线名 ,工位
            d_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.pdf_dict["update_time"] = d_time
            self.sync_db(self.pdf_dict)    # 数据库方入数据库
            # print(self.pdf_dict)
            # self.pdf_dict["is_alter"] = 0
            # self.H_photo_data(self.pdf_dict, pdf_data)
            # self.get_List(self.pdf_dict)      # 数据转字典, 报错到表格

    # 数据转为列表
    def get_List(self, pdf_dict):
        pdf_dict["is_alter"] = 0
        pdf_dict["alter_item"] = "REQ:55"
        pdf_dict["scan_time"] = "12.01"

        pdf_list = [pdf_dict["RMC_bar"], pdf_dict["ticket_bar"], pdf_dict["plant"], pdf_dict["data"],
                    pdf_dict["time"], pdf_dict["demand"], pdf_dict["BOX"], pdf_dict["BOX_num"], pdf_dict["REQ"],
                    pdf_dict["serial_num"], pdf_dict["invoice_time"], pdf_dict["area_code"], pdf_dict["lineName"],
                    pdf_dict["station"], pdf_dict["is_alter"], pdf_dict["alter_item"], pdf_dict["scan_time"]]
        self.all_List.append(pdf_list)


    # 模仿搞怕仪数据
    def H_photo_data(self, pdf_dict, pdf_data):
        self.H_data.update({
            pdf_data[1]: {
                pdf_dict["RMC_bar"]: self.pdf_dict
            }
        })
        del self.H_data[pdf_data[1]][pdf_dict["RMC_bar"]]["RMC_bar"]
        del self.H_data[pdf_data[1]][pdf_dict["RMC_bar"]]["ticket_bar"]

    # 数据放入数据库
    def sync_db(self, pdf_dict):
        print("插入数据库数据: ", pdf_dict)
        as400_sync(pdf_dict)
        print("数据插入成功!!!>>>")
        time.sleep(0.5)


    def start_run(self):
        self.H_data = {}
        self.pdf_dict = {}
        for page in self.pdf.pages:
            try:
                # 获取当前页面的全部文本信息，包括表格中的文字
                pdf_data = page.extract_text().strip().replace("\n", ",")
                pdf_data = pdf_data.split(",")[1:-2]  # 去除 字符串: "出张出库"  和尾部多余的字符
                del pdf_data[4]
                pdf_data = self.del_EG(pdf_data)
                self.get_RMC(pdf_data)
            except Exception as e:
                pass
        print(self.all_List)
        Table_Hear = ["RMC_bar", "ticket_bar", "plant", "data", "time", "demand", "BOX", "BOX_num",
                      "REQ", "serial_num", "invoice_time","area_code", "lineName", "station"]
        df = pd.DataFrame(self.all_List, columns=Table_Hear)
        df.to_csv("123.csv", index=False)
        self.pdf.close()
        return self.H_data

# run_obj = PDF_EXCEL()

if __name__=="__main__":
    while True:
        run_obj = PDF_EXCEL()
        run_obj.start_run()
        time.sleep(1)

